import smtplib
import os
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from config.config import Config
from common.consts import REPORT_PATH
from common.log import Log

c = Config()
logger = Log.get_logger()


def send_email(report):
    msg = MIMEMultipart()
    msg["Subject"] = c.get_email("subject")
    msg["From"] = c.get_email("user")
    msg["To"] = c.get_email("receiver")
    with open(os.path.join(REPORT_PATH, report), 'rb') as f:
        body = f.read()
        attach = MIMEBase('zip', 'zip', filename=report)
        attach.add_header('Content-Disposition', 'attachment', filename=('gb2312', '', report))
        attach.set_payload(body)
        encoders.encode_base64(attach)
        msg.attach(attach)
    try:
        smtp = smtplib.SMTP()
        smtp.connect(c.get_email("server"))
        smtp.login(c.get_email("user"), c.get_email("pwd"))
        smtp.sendmail(c.get_email("user"), c.get_email("receiver"), msg.as_string())

    except Exception as e:
        print(e)
        print("发送失败")
        logger.eror("邮件发送失败")
    else:
        print('发送成功')
        logger.info("邮件发送成功")
    finally:
        smtp.quit()


if __name__ == '__main__':
    send_email('xxx')
